import { mat4 } from "cc";
import { allColumn, allRow, beginX, beginY, cellHeight, cellWidth, LayerInfo } from "../core/GameConst";
import { PosInfo } from "../core/PosInfo";

export default class GameUtils{


    public static getRandomOne<T>(arr:T[]):T
    {
        if (arr == null || arr.length == 0) {
            return null;
        }
        return arr[ Math.floor(Math.random()*(arr.length-1))];
    }

    /**delay一个时间会回调*/
    public static wait(ms: number): Promise<void> {
        return new Promise(resolve => {
            setTimeout(resolve, ms);
        });
    }



    /**
     * 随机获取一个卡片的位置,笨方法，以后优化
     * 卡牌之间不叠放
     */
    public static getRandomPos(layer:LayerInfo = null):PosInfo {
        let row:number = Math.floor(Math.random() * (allRow - 1));
        let column:number = Math.floor(Math.random() * (allColumn - 1));
        if ((allRow-1) - row == 0) {
            row -= Math.floor(Math.random() * (allRow - 1));
        }
        if ((allColumn-1) - column == 0) {
            column -= Math.floor(Math.random() * (allColumn - 1));
        }

        //这个位置有卡牌了，重新来，先这样吧，笨方法
        if (this.thisPosOverlapForOneLayer(column,row,layer)) {
            return this.getRandomPos(layer);
        }else{
            let info:PosInfo = new PosInfo();
            info.gridX = column;
            info.gridY = row;

            info.pixelX = beginX + column * cellWidth + cellWidth; //最后这个是卡牌的半个宽度
            info.pixelY = beginY - (row * cellHeight) - cellHeight;

            // info.pixelX = info.pixelX + (layer.layerId%10)*3; //不同layer的层偏移量，好看一点，不会完全覆盖
            // info.pixelY = info.pixelY - (layer.layerId%10)*3; //不同layer的层偏移量，好看一点，不会完全覆盖
            return info;
        }
    }



    /**
     * 这个位置是否重叠了其他卡牌，针对同一层
     * true 为重叠了，false为没重叠
     */
    private static thisPosOverlapForOneLayer(gridX:number, gridY:number, layer:LayerInfo = null):boolean {
        if (layer == null) {
            return false;
        }
        let beginX:number = Math.max(gridX - 1, 0); 
        let beginY:number = Math.max(gridY - 1, 0); 
        let endX:number = Math.min(gridX + 1, allColumn-1); 
        let endY:number = Math.min(gridY + 1, allColumn-1); 
        for (let x:number = beginX; x <= endX; x++) {
            for (let y:number = beginY; y <= endY; y++) {
                if (layer.allCards.get(`${x}_${y}`) != null){
                    return true;
                }
            }
        }
        console.log(`找到一个位置${gridX}_${gridY},判断范围${beginX}_${beginY}---${endX}_${endY}`);
        return false;
    }

}
